package fu.k4c.vTeam.Main;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Manage.EditEventActivity;
import fu.k4c.vTeam.Manage.EditPlaceActivity;
import fu.k4c.vTeam.Object.AllInformationPlace;

public class ViewManagerActivity extends BaseActivity {
	String email;
	EditText et_search;
	int textlength = 0;
	GridView gv_categories;
	ProgressDialog proDialog;
	List<AllInformationPlace> yourClassList;
	private DisplayImageOptions options;
	static final private int CHOOSE_EDIT = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_manager_activity);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.stub_image)
				.showImageForEmptyUri(R.drawable.image_for_empty_url)
				.cacheInMemory().cacheOnDisc()
				.displayer(new RoundedBitmapDisplayer(20)).build();
		gv_categories = (GridView) findViewById(R.id.gv_view_manager);
		Button btn_back = (Button) findViewById(R.id.btn_view_manager_back);
		btn_back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		Bundle data = getIntent().getExtras();
		if (data != null) {
			email = data.getString("email");

		}
		getdata(email);
		et_search = (EditText) findViewById(R.id.et_view_manager_search);
		et_search.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence cs, int arg1, int arg2,
					int arg3) {
				// When user changed the Text
				textlength = et_search.getText().length();
				final List<AllInformationPlace> listSearch = new ArrayList<AllInformationPlace>();
				;
				for (int i = 0; i < yourClassList.size(); i++) {
					if (yourClassList.get(i).getName().toLowerCase()
							.indexOf(et_search.getText().toString()) >= 0
							|| yourClassList.get(i).getAddress().toLowerCase()
									.indexOf(et_search.getText().toString()) >= 0) {
						listSearch.add(yourClassList.get(i));
					}
				}
				ListPlaceManager adapter = new ListPlaceManager(
						ViewManagerActivity.this, listSearch);
				gv_categories.setAdapter(adapter);
				gv_categories.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> arg0, View v,
							int position, long id) {
						if (listSearch.get(position).getCategoriesID()
								.equals("196")) {
							Intent i = new Intent(ViewManagerActivity.this,
									EditEventActivity.class);
							i.putExtra("address", listSearch.get(position)
									.getAddress());
							i.putExtra("placename", listSearch.get(position)
									.getName());
							i.putExtra("placetel", listSearch.get(position)
									.getPhone());
							i.putExtra("des", listSearch.get(position)
									.getDescription());
							i.putExtra("lat", listSearch.get(position)
									.getLatitude());
							i.putExtra("long", listSearch.get(position)
									.getLongitude());
							i.putExtra("IDofItemRevision",
									listSearch.get(position).getIdPlace());
							i.putExtra("cityID", listSearch.get(position)
									.getCityID());
							i.putExtra("username", email);
							i.putExtra("startDate", listSearch.get(position)
									.getStartDate());
							i.putExtra("startTime", listSearch.get(position)
									.getStartTime());
							i.putExtra("endDate", listSearch.get(position)
									.getEndDate());
							i.putExtra("endTime", listSearch.get(position)
									.getEndTime());
							startActivityForResult(i, CHOOSE_EDIT);
						} else {
							Intent i = new Intent(ViewManagerActivity.this,
									EditPlaceActivity.class);
							i.putExtra("address", listSearch.get(position)
									.getAddress());
							i.putExtra("placename", listSearch.get(position)
									.getName());
							i.putExtra("placetel", listSearch.get(position)
									.getPhone());
							i.putExtra("des", listSearch.get(position)
									.getDescription());
							i.putExtra("lat", listSearch.get(position)
									.getLatitude());
							i.putExtra("long", listSearch.get(position)
									.getLongitude());
							i.putExtra("Categories", listSearch.get(position)
									.getCategorieName());
							i.putExtra("IDofItemRevision",
									listSearch.get(position).getIdPlace());
							i.putExtra("cityID", listSearch.get(position)
									.getCityID());
							i.putExtra("username", email);
							startActivityForResult(i, CHOOSE_EDIT);
						}
					}
				});

			}

			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
			}
		});
	}

	private void getdata(String mEmail) {
		// TODO Auto-generated method stub
		try {
			proDialog = ProgressDialog.show(ViewManagerActivity.this, "",
					"Đang tải dữ liệu...");
			new Thread() {
				public void run() {

					try {
						sleep(1000);

					} catch (Exception e) {
						System.out.print(e.toString());
					}
					proDialog.dismiss();
				}
			}.start();
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			HttpParams httpParams = new BasicHttpParams();
			ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
					httpParams, registry);
			HttpClient client = new DefaultHttpClient(connMgr, httpParams);
			HttpPost post = new HttpPost(getString(R.string.connectionString)
					+ "vLocationService/getcreateplacebyuser");
			post.setHeader("Accept", "application/json");
			post.setHeader("Content-type", "application/json");
			HashMap<String, Object> postParameters = new HashMap<String, Object>();
			postParameters.put("UserName", mEmail);
			postParameters.put("TypeOfRequest", "");
			Gson gson = new Gson();
			String jsonParameters = gson.toJson(postParameters);
			post.setEntity(new StringEntity(jsonParameters));
			HttpResponse response = client.execute(post);

			HttpEntity entity = response.getEntity();
			String jsonresult = EntityUtils.toString(entity);

			try {
				Type listType = new TypeToken<ArrayList<AllInformationPlace>>() {
				}.getType();
				yourClassList = new Gson().fromJson(jsonresult, listType);
				if (yourClassList.size() == 0) {
					Toast.makeText(getApplicationContext(),
							"Không có kết quả nào", Toast.LENGTH_LONG).show();
				}

				ListPlaceManager adapter = new ListPlaceManager(this,
						yourClassList);
				gv_categories.setAdapter(adapter);
				gv_categories.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> arg0, View v,
							int position, long id) {
						if (yourClassList.get(position).getCategoriesID()
								.equals("196")) {
							Intent i = new Intent(ViewManagerActivity.this,
									EditEventActivity.class);
							i.putExtra("address", yourClassList.get(position)
									.getAddress());
							i.putExtra("placename", yourClassList.get(position)
									.getName());
							i.putExtra("placetel", yourClassList.get(position)
									.getPhone());
							i.putExtra("des", yourClassList.get(position)
									.getDescription());
							i.putExtra("lat", yourClassList.get(position)
									.getLatitude());
							i.putExtra("long", yourClassList.get(position)
									.getLongitude());
							i.putExtra("IDofItemRevision",
									yourClassList.get(position).getIdPlace());
							i.putExtra("cityID", yourClassList.get(position)
									.getCityID());
							i.putExtra("username", email);
							i.putExtra("startDate", yourClassList.get(position)
									.getStartDate());
							i.putExtra("startTime", yourClassList.get(position)
									.getStartTime());
							i.putExtra("endDate", yourClassList.get(position)
									.getEndDate());
							i.putExtra("endTime", yourClassList.get(position)
									.getEndTime());
							startActivityForResult(i, CHOOSE_EDIT);
						} else {
							Intent i = new Intent(ViewManagerActivity.this,
									EditPlaceActivity.class);
							i.putExtra("address", yourClassList.get(position)
									.getAddress());
							i.putExtra("placename", yourClassList.get(position)
									.getName());
							i.putExtra("placetel", yourClassList.get(position)
									.getPhone());
							i.putExtra("des", yourClassList.get(position)
									.getDescription());
							i.putExtra("lat", yourClassList.get(position)
									.getLatitude());
							i.putExtra("long", yourClassList.get(position)
									.getLongitude());
							i.putExtra("Categories", yourClassList
									.get(position).getCategorieName());
							i.putExtra("IDofItemRevision",
									yourClassList.get(position).getIdPlace());
							i.putExtra("cityID", yourClassList.get(position)
									.getCityID());
							i.putExtra("username", email);
							startActivityForResult(i, CHOOSE_EDIT);
						}
					}
				});

			} catch (Exception e) {
				Toast.makeText(getApplicationContext(),
						"Loi : " + e.toString(), Toast.LENGTH_LONG).show();
				// TODO: handle exception
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && requestCode == CHOOSE_EDIT) {
			getdata(email);
		}
	}

	public class ListPlaceManager extends BaseAdapter {
		Activity ListViewManager;
		List<AllInformationPlace> data;
		ViewHolder holder = new ViewHolder();
		ViewHolder2 holder2 = new ViewHolder2();

		private class ViewHolder {
			public TextView tv_name;
			public TextView tv_phone;
			public TextView tv_address;
			public TextView tv_view;
			public ImageView imv_avatar;
		}

		private class ViewHolder2 {
			public TextView tv_name;
			public TextView tv_phone;
			public TextView tv_address;
			public TextView tv_view;
			public TextView tv_start;
			public TextView tv_end;
			public ImageView imv_avatar;
		}

		public ListPlaceManager(Activity mListCategoriesView,
				List<AllInformationPlace> mdata) {
			ListViewManager = mListCategoriesView;
			data = mdata;

		}

		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return data.get(position);
		}

		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		public View getView(int position, View convertView, ViewGroup arg2) {
			// TODO Auto-generated method stub

			View view1 = convertView;
			View view2 = convertView;
			if (data.get(position).getCategoriesID().equals("196")) {

				view2 = getLayoutInflater().inflate(R.layout.row_event, null);
				holder2.tv_name = (TextView) view2
						.findViewById(R.id.tv_row_event_name);
				holder2.tv_phone = (TextView) view2
						.findViewById(R.id.tv_row_event_phone);
				holder2.tv_address = (TextView) view2
						.findViewById(R.id.tv_row_event_address);
				holder2.tv_view = (TextView) view2
						.findViewById(R.id.tv_row_event_views);
				holder2.tv_start = (TextView) view2
						.findViewById(R.id.tv_row_event_start);
				holder2.tv_end = (TextView) view2
						.findViewById(R.id.tv_row_event_end);
				holder2.imv_avatar = (ImageView) view2
						.findViewById(R.id.imv_row_event);
				view2.setTag(holder2);
				String imageurl2;
				if (data.get(position).getAvatar() != null) {
					if (data.get(position).getAvatar().toLowerCase()
							.indexOf("http://") >= 0) {
						imageurl2 = data.get(position).getAvatar();

					} else {
						imageurl2 = getString(R.string.connectionString)
								+ data.get(position).getAvatar();
					}
				} else {
					imageurl2 = data.get(position).getAvatar();
				}
				imageLoader.init(ImageLoaderConfiguration
						.createDefault(getBaseContext()));
				imageLoader.displayImage(imageurl2, holder2.imv_avatar,
						options, new SimpleImageLoadingListener() {
							@Override
							public void onLoadingComplete(Bitmap loadedImage) {
								Animation anim = AnimationUtils.loadAnimation(
										ViewManagerActivity.this,
										R.anim.fade_in);
								holder2.imv_avatar.setAnimation(anim);
								anim.start();
							}
						});
				holder2.tv_name.setText(data.get(position).getName());
				holder2.tv_start.setText("Bắt đầu : "
						+ data.get(position).getStartDate());
				holder2.tv_end.setText("Kết thúc : "
						+ data.get(position).getEndDate());
				if (data.get(position).getPhone() == null) {
					holder2.tv_phone.setText("Số điện thoại : N\\A");
				} else
					holder2.tv_phone.setText("Số điện thoại : "
							+ data.get(position).getPhone());
				holder2.tv_address.setText("Địa chỉ : "
						+ data.get(position).getAddress());
				holder2.tv_view.setText("Lượt xem : "
						+ data.get(position).getViews());
				return view2;
			} else {
				view1 = getLayoutInflater().inflate(
						R.layout.row_view_by_categories, null);
				holder.imv_avatar = (ImageView) view1
						.findViewById(R.id.imv_row_view);
				holder.tv_name = (TextView) view1
						.findViewById(R.id.tv_row_view_name);
				holder.tv_phone = (TextView) view1
						.findViewById(R.id.tv_row_view_phone);
				holder.tv_address = (TextView) view1
						.findViewById(R.id.tv_row_view_address);
				holder.tv_view = (TextView) view1
						.findViewById(R.id.tv_row_view_views);
				view1.setTag(holder);
				String imageurl;
				if (data.get(position).getAvatar() != null) {
					if (data.get(position).getAvatar().toLowerCase()
							.indexOf("http://") >= 0) {
						imageurl = data.get(position).getAvatar();

					} else {
						imageurl = getString(R.string.connectionString)
								+ data.get(position).getAvatar();
					}
				} else {
					imageurl = data.get(position).getAvatar();
				}
				imageLoader.init(ImageLoaderConfiguration
						.createDefault(getBaseContext()));
				imageLoader.displayImage(imageurl, holder.imv_avatar, options,
						new SimpleImageLoadingListener() {
							@Override
							public void onLoadingComplete(Bitmap loadedImage) {
								Animation anim = AnimationUtils.loadAnimation(
										ViewManagerActivity.this,
										R.anim.fade_in);
								holder.imv_avatar.setAnimation(anim);
								anim.start();
							}
						});
				holder.tv_name.setText(data.get(position).getName());
				if (data.get(position).getPhone() == null) {
					holder.tv_phone.setText("Số điện thoại : N\\A");
				} else
					holder.tv_phone.setText("Số điện thoại : "
							+ data.get(position).getPhone());
				holder.tv_address.setText("Địa chỉ : "
						+ data.get(position).getAddress());
				holder.tv_view.setText("Lượt xem : "
						+ data.get(position).getViews());
				return view1;
			}

		}
	}

}
